'''

1、通过程序，扫描被进程占用的端口（TCP及UDP）和进程相关信息，并输出。
2、输出结果包括：进程id（pid）、进程名、占用端口、端口类型、Local IP、进程地址。

'''

import psutil


def get_process_info():

    # 获取当前的网络连接信息
    net_con = psutil.net_connections()
    port_type =''
    for con_info in net_con:
        pid = con_info[6]
        ip = con_info[3].ip
        port = con_info[3].port
        if con_info[2] == 1:
            port_type = 'TCP'
        elif con_info[2] == 2:
            port_type = 'UDP'
        # 进程对象
        p = psutil.Process(con_info[6])
        # 进程名
        process_name = p.name()
        process_addr = p.open_files()
        print('pid: %-8s 进程名: %-20s 占用端口: %-8s 端口类型: %-8s Local IP: %-20s 进程地址: %s' %
              (pid,process_name,port,port_type,ip,process_addr))


if __name__ == "__main__":
    get_process_info()
    # net_con = psutil.net_connections()
    # for con_info in net_con:
    #     print(con_info)